package cn.livingCloud.service.impl.operation;

import cn.livingCloud.context.BeanProvider;
import cn.livingCloud.dto.CaseFormDto;
import cn.livingCloud.dto.CaseImageDto;
import cn.livingCloud.entity.core.Case;
import cn.livingCloud.entity.core.CaseImage;
import cn.livingCloud.repository.CaseImageMapper;
import cn.livingCloud.repository.CaseMapper;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by DingJie on 2016/6/3.
 */
public class CaseFormDtoUpdater {
    protected transient CaseMapper mapper = BeanProvider.getBean(CaseMapper.class);
    protected transient CaseImageMapper imageMapper = BeanProvider.getBean(CaseImageMapper.class);
    private CaseFormDto formDto;

    public CaseFormDtoUpdater(CaseFormDto formDto) {
        this.formDto = formDto;
    }

    public CaseFormDto getFormDto() {
        return formDto;
    }

    public void setFormDto(CaseFormDto formDto) {
        this.formDto = formDto;
    }

    public void update() {
        if (StringUtils.isEmpty(formDto.getUuid())) {
            String uuid = createCase();
            createCasesImage(uuid);
        } else {
            Case aCase = mapper.selectByPrimaryKey(formDto.getUuid());
            updateCase(aCase);
            updateCaseImage();
        }
    }

    protected void updateCaseImage() {
        imageMapper.deleteByPrimaryKey(formDto.getUuid());
        createCasesImage(formDto.getUuid());
    }

    protected void updateCase(Case aCase) {
        aCase.setPhone(formDto.getPhone())
                .setAddressDescription(formDto.getAddressDescription())
                .setLocationX(formDto.getLocationX())
                .setLocationY(formDto.getLocationY());
        mapper.updateByPrimaryKey(aCase);
    }

    protected void createCasesImage(String uuid) {
        List<CaseImageDto> imageList = formDto.getImageList();
        for (CaseImageDto caseImageDto : imageList) {
            if (StringUtils.isEmpty(caseImageDto.getUrl())) {
                continue;
            }
            CaseImage caseImage = new CaseImage().setCaseUuid(uuid).setUrl(caseImageDto.getUrl());
            imageMapper.insert(caseImage);
//            weixin://resourceid/9f3bd592015e149eb56c05d38dab5331
            new CaseImageDownloadHandler(caseImage).handler();
        }
    }

    protected String createCase() {
        Case aCase = new Case();
        aCase.setAddressDescription(formDto.getAddressDescription())
                .setPhone(formDto.getPhone())
                .setLocationX(formDto.getLocationX())
                .setLocationY(formDto.getLocationY()).setCreatorUuid(formDto.getCreatorUuid());
        mapper.insert(aCase);
        return aCase.getUuid();
    }
}
